package it.unibz.inf.cn;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class Request {
	
	public static final String GET = "GET";
	public static final String  POST = "POST";

	public static HttpURLConnection getHttpURLConnection(String url) {
		return Request.getHttpURLConnection(url, null);
	}
	
	public static HttpURLConnection getHttpURLConnection(String url, String type) {
		HttpURLConnection httpURLConnection = null;
		try {
			// Open http connection to the specified url
			httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
			// Specify transfer method
			if (type != null && type.equals(Request.POST)) {
				httpURLConnection.setRequestMethod(Request.POST);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return httpURLConnection;
	}
	
	public static Document getDocument(HttpURLConnection httpURLConnection) {
		Document doc = null;
		try {
			// Create a DOM from the request document in order to parse the result
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(httpURLConnection.getInputStream());
		    doc.getDocumentElement().normalize();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	    
	    return doc;
	}
}
